<?php

namespace app\selladmin\controller;

use app\selladmin\controller\CommonController;
use app\selladmin\model\Staff;
use app\selladmin\model\Store;
use app\util\Utils;
use app\util\Easemob;
use app\selladmin\model\Code;
use think\Validate;
use app\selladmin\model\Admin;
use app\selladmin\model\StoreSaveRecord;
use app\selladmin\model\Order;
use app\selladmin\model\CtmStaff;
use app\selladmin\model\Custom;
use think\Db;

class StaffController extends CommonController {
    /*
     * 员工列表 
     * author xfwed
     * date 2017.08.09   
     */

    public function StaffList() {
        //查询员工信息
        $staff = new Staff();
        $telephone = input('get.telephone');
        $staffList = $staff->StaffInfo('', $telephone, 18);
        $aa = ($staffList->toArray()['data']);
        for ($i = 0; $i < count($aa); $i++) {
            //查询店铺信息
            $store = new Store();
            $aa[$i]['storeinfo'] = $store->StoreInfo($aa[$i]['store_id']);
        }
        return view('stafflist', [
            'aa' => $aa,
            'staffList' => $staffList,
            'telephone' => $telephone,
        ]);
    }

    /*
     * 更换手机号
     * author xfwed
     * date 2017.09.17
     */

    public function changePhone() {
        //查询员工信息
        $staff = new Staff();
        $id = input('param.id');
        $staffrow = $staff->where("id=" . $id)->field('id,telephone')->find();

        return view('changephone', [
            'staffList' => $staffrow,
        ]);
    }

    /*
     * 更换手机号
     * author xfwed
     * date 2017.09.17
     */

    public function changePhoneExe() {
        //查询员工信息
        $staff = new Staff();
        $all = input('param.');
        $id = $all['id'];
        $newphone = $all['newphone'];
        $code = $all['code'];
        //return $this->ajaxReturn(0, '短信发送成功', $newphone);
        //验证验证码
        $lastRow = Code::where('type', '=', Code::TYPE_31)
                ->where('telephone', '=', $newphone)
                ->field('id, code, status, add_time')
                ->order('add_time desc')
                ->find();
        if (is_null($lastRow)) {
            return $this->ajaxReturn(40015, '未发送验证码', null);
        }

        //验证码已过期 = 超过15分钟 + 已使用 + 输入旧验证码
        $now = time();
        if (($now - $lastRow['add_time']) > 900) {
            return $this->ajaxReturn(40016, '验证码已过期', null);
        }
        if ($lastRow['status'] == Code::STATUS_2) {
            return $this->ajaxReturn(40017, '验证码已使用', null);
        }
        $codeRow = Code::where('type', '=', Code::TYPE_31)
                ->where('telephone', '=', $newphone)
                ->where('code', '=', $code)
                ->where('add_time', '<', $lastRow['add_time'])
                ->order('add_time desc')
                ->find();
        if (!is_null($codeRow)) {
            return $this->ajaxReturn(40018, '验证码已过期', null);
        }

        if ($lastRow['code'] == $code) {
            Code::where('id', '=', $lastRow['id'])->update(['status' => Code::STATUS_2]);
        } else {
            return $this->ajaxReturn(40019, '验证码错误', null);
        }

        //查询手机号是否注册过
        $oldstafflist = $staff->where('telephone', '=', $newphone)->where('staff_on', '=', 1)->field('id')->find();
        if ($oldstafflist) {
            return $this->ajaxReturn(40030, '该手机号已注册', null);
        }

        //循环修改环信账号
        $stafflist = $staff->where('id', '=', $id)->field('store_id,telephone,staff_pwd')->find();
        $easemob = new Easemob();
        //给员工注册环信
        $easemob->createUser('sh'.$newphone . $stafflist['store_id'], $stafflist['staff_pwd']);
        //删除原有环信账号
        $easemob->deleteUser('sh'.$stafflist['telephone'] . $stafflist['store_id']);

        $result = $staff->where('id', '=', $id)->update(['telephone' => $newphone]);
        $store = new Store();
        $store->where('id', '=', $stafflist['store_id'])->update(['keeper_phone' => $newphone]);

        //写入修改记录
        $storesaverecord = new StoreSaveRecord();
        $store_id = $stafflist['store_id'];
        $old = $stafflist['telephone'];
        $new = $newphone;
        $record = $storesaverecord->insertRecord($store_id, $old, $new);

        if ($result) {
            return $this->ajaxReturn(0, '更换手机号成功', null);
        } else {
            return $this->ajaxReturn(40024, '更换手机号失败', null);
        }
    }

    /*
     * 发送验证码（更换手机号）
     * author xfwed
     * date 2017-09-19
     */

    public function sendCode() {
        $rule = [
            'telephone' => 'require|length:11',
            'type' => 'require|in:31',
        ];
        $msg = [
            'telephone.require' => '手机号必须',
            'telephone.length' => '手机号长度为11',
            'type.require' => '类型必须',
            'type.in' => '类型为31',
        ];

        $all = input('post.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return $this->ajaxReturn(1, $error, null);
        }

        $telephone = $all['telephone'];
        $type = $all['type'];
        $canSend = Code::canSendCode($telephone, $type);
        if (!$canSend) {
            return $this->ajaxReturn(40013, '验证码发送频繁', null);
        }

        $code = mt_rand(1000, 9999);
        $content = '您更换手机号的验证码是' . $code . '，验证码有效期15分钟';
        $sendResult = Utils::sendSms($telephone, $content);
        if ($sendResult['code'] == 'success') {
            //写入验证码
            $codeData = [
                'type' => $type,
                'telephone' => $telephone,
                'code' => $code,
                'status' => Code::STATUS_1,
                'times' => 1,
                'add_time' => time(),
            ];

            Code::insert($codeData);

            return $this->ajaxReturn(0, '验证码发送成功', null);
        } else {
            return $this->ajaxReturn(40014, $sendResult['msg'], null);
        }
    }

    /*
     * 修改支付宝
     * author xfwed
     * date 2017.10.18
     */

    public function changealipay() {
        //查询员工信息
        $staff = new Staff();
        $all = input('param.');
        $id = $all['id'];
        //查询手机号是否注册过
        $staffdata = $staff->where('id', '=', $id)->field('id,zfb,zfb_name')->find();

        if (!$_POST) {
            return view('changealipay', ['staffdata' => $staffdata]);
        } else {
            $rule = [
                'zfb' => 'require',
                'zfb_name' => 'require',
                'adminname' => 'require',
            ];
            $msg = [
                'zfb.require' => '店铺名称必须',
                'zfb_name.require' => '店铺电话必须',
                'adminname.require' => '请输入你的密码',
            ];
            $all = input('post.');
            $validate = new Validate($rule, $msg);

            if (!$validate->check($all)) {
                $error = $validate->getError();
                $this->error($error);
            }
            //验证添加者身份
            $addid = session('A_ID');
            $adminfind = Admin::where('id=' . $addid)->find();
            if ($adminfind['admin_pwd'] != md5($all['adminname'])) {
                $this->error('你的密码错误，修改失败');
            }
            $data['zfb'] = $all['zfb'];
            $data['zfb_name'] = $all['zfb_name'];
            $result = $staff->where('id', '=', $id)->update($data);
            if ($result) {
                $this->success('修改成功');
            } else {
                $this->success('修改失败');
            }
        }
    }
    
     /*
     * 员工分析
     * author xfwed
     * date 2018-01-16
     * */

    public function StaffEcharts() {
        $year = isset($_REQUEST['year']) ? $_REQUEST['year'] : date('Y');
        //月份
        for ($m = 1; $m <= 12; $m++) {
            $month[] = $m . "月";
        }

        //员工量（总）
        $staffData = Staff::where("FROM_UNIXTIME(add_time,'%Y') = '" . $year . "'")
                ->where('staff_on','=',1)
                ->field("FROM_UNIXTIME(add_time, '%m') AS m,count(id) AS c")
                ->group('m')
                ->order('m asc')
                ->select();
        $staffReturn_data = array(
            '01' => 0, '02' => 0, '03' => 0, '04' => 0, '05' => 0, '06' => 0, '07' => 0, '08' => 0, '09' => 0, '10' => 0, '11' => 0, '12' => 0,
        );
        foreach ($staffData as $value) {
            $staffReturn_data[$value['m']] = $value['c'];
        }

        //员工量（男）
        $staffData1 = Staff::where("FROM_UNIXTIME(add_time,'%Y') = '" . $year . "'")
                ->where('staff_sex', '=', 1)
                ->where('staff_on','=',1)
                ->field("FROM_UNIXTIME(add_time, '%m') AS m,count(id) AS c")
                ->group('m')
                ->order('m asc')
                ->select();
        $staffReturn_data1 = array(
            '01' => 0, '02' => 0, '03' => 0, '04' => 0, '05' => 0, '06' => 0, '07' => 0, '08' => 0, '09' => 0, '10' => 0, '11' => 0, '12' => 0,
        );
        foreach ($staffData1 as $value) {
            $staffReturn_data1[$value['m']] = $value['c'];
        }

        //员工量（女）
        $staffData2 = Staff::where("FROM_UNIXTIME(add_time,'%Y') = '" . $year . "'")
                ->where('staff_sex', '=', 2)
                ->where('staff_on','=',1)
                ->field("FROM_UNIXTIME(add_time, '%m') AS m,count(id) AS c")
                ->group('m')
                ->order('m asc')
                ->select();
        $staffReturn_data2 = array(
            '01' => 0, '02' => 0, '03' => 0, '04' => 0, '05' => 0, '06' => 0, '07' => 0, '08' => 0, '09' => 0, '10' => 0, '11' => 0, '12' => 0,
        );
        foreach ($staffData2 as $value) {
            $staffReturn_data2[$value['m']] = $value['c'];
        }


        $currentYear = date('Y');
        $years = $currentYear + 1;

        return view('staffecharts', [
            'month' => implode(',', $month),
            'staffData' => implode(',', array_values($staffReturn_data)),//员工量总
            'staffData1' => implode(',', array_values($staffReturn_data1)),//员工量男
            'staffData2' => implode(',', array_values($staffReturn_data2)),//员工量女
            'years' => $years,
            'year' => $year,
            'currentYear' => $currentYear
        ]);
    }
    
    /*
     * 解锁
     * author xfwed
     * date 2018-07-14   
     */
    public function Unlocking(){
        $id=  input('param.id');
        $data['error_nums']=0;
        $data['error_time']='';
        $updata=Staff::where('id','=',$id)->update($data);
        if($updata){
            return $this->ajaxReturn(0, '解锁成功', null);
        }  else {
            return $this->ajaxReturn(1, '不需要解锁', null);
        }
    }
    
    /*
     *员工业绩  体验卡 会员卡 服务人数  服务人次
     * author xfwed 
     * date 2019-01-07      
     */
    public function Yeji(){
        $id = input('param.id');
        $store_id = input('param.store_id');
        $starttime = input('param.starttime');
        $endtime = input('param.endtime');
        if ($endtime && $starttime) {
            $time = strtotime($starttime);
            $time2 = strtotime($endtime) + 24 * 60 * 60;
            $where['pay_time'] = array('between', array($time, $time2));
            $where2['add_time'] = array('between', array($time, $time2));
            $where3['end_time'] = array('between', array($time, $time2));
        } elseif (empty($endtime) && $starttime) {
            $time = strtotime($starttime);
            $time2 = $time + 24 * 60 * 60;
            $where['pay_time'] = array('between', array($time, $time2));
            $where2['addy_time'] = array('between', array($time, $time2));
            $where3['end_time'] = array('between', array($time, $time2));
        }
        $where = isset($where) ? $where : [];
        $where2 = isset($where2) ? $where2 : [];
        $where3 = isset($where3) ? $where3 : [];
        //查询店铺信息
        $store = new Store();
        $storeList = $store->StoreInfo($id);
        //查询员工的体验卡数量
        $orderdata=Order::where('type','=',4)
                ->where('status',">",1)
                ->where('store_id','=',$store_id)
                ->where($where)
                ->select();
        $tiyannum=0;
        for($i=0;$i<count($orderdata);$i++){
           $ctmstaff=CtmStaff::where('status','>=',4)
                   ->where('order_id','=',$orderdata[$i]['id'])
                   ->order('add_time asc')
                   ->find();
           if($ctmstaff['staff_id']==$id){
               $tiyannum=$tiyannum+1;
           }
        }
        //查询员工的会员卡数量
        $ctmids=Custom::where('store_id','=',$store_id)->where('status','=',2)->column('id');
        $ctmvip=Db::name('ctm_vip')->where('ctm_id','in',$ctmids)->where($where2)->select();
        $vipnum=0;
        for($j=0;$j<count($ctmvip);$j++){
            $orderdata1=Order::where('vip_id','=',$ctmvip[$j]['vipcard_id'])
                ->where('status',">",1)
                ->where('store_id','=',$store_id)
                ->column('id');
            $ctmstaff=CtmStaff::where('status','>=',4)
                    ->where('order_id','in',$orderdata1)
                    ->order('add_time asc')
                    ->find();
            if($ctmstaff['staff_id']==$id){
                $vipnum=$vipnum+1;
            }
        }
        //查询员工的服务人数
        $list = Db::name('ctm_staff')->where('staff_id', '=', $id)
                ->where('status', '>=', 9)
                ->where($where3)
                ->group('ctm_id')
                ->select();
        $renshunum=  count($list);
        //查询员工的服务人次
        $count = Db::name('ctm_staff')->where('staff_id', '=', $id)
                ->where('status', '>=', 9)
                ->where($where3)
                ->count();
        $rencinum=$count;
        
        return view('yeji', [
            'storeList' => $storeList,
            'id' => $id,
            'store_id' => $store_id,
            'starttime' => $starttime,
            'endtime' => $endtime,
            'tiyannum' => $tiyannum,
            'vipnum' => $vipnum,
            'renshunum' => $renshunum,
            'rencinum' => $rencinum,
        ]);
    }

}
